' Animals Initial Review Validation Script
Option Strict Off
imports System
imports Humans=PHSRAG.Insight21.Humans
imports PHSRAG.Insight21.BusinessObjects
imports FormsManagement = PHSRAG.Insight21.FormsManagement
imports System.Collections
imports Utility=PHSRAG.Utility

module Script
    sub Main()

        ' Pages for rediction
        const staffPageRedirection = 0
        const overviewPageRedirection = -2
		const AttachmentsPageRedirection = -1
        
   		'variable to store the documents needed
		Dim documentsToBeAttached As new ArrayList() 
		dim attachmentsLogItemAdded as boolean = false


        if intrinsicProtocol.PIPersonId = 0 then ' if no PI, log that error, else, log org error
            Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
            logItem.QuestionnaireVersionId = staffPageRedirection
            logItem.QuestionnaireAnswerId = staffPageRedirection
            logItem.Type = "Staff"
            logItem.Category = "No PI"
            logItem.QuestionName ="Staff"
            logItem.Answer = "Staff"
            logItem.Description = "Protocol must have a staffed Principal Investigator"
            logItem.Completed = False
            SaveLogItem(logItem)
        end if

        'Check if Flowchart is attached. This document is required for all the protocols
        Dim attachedDocuments As ArrayList = intrinsicProtocolProcess.ProtocolDocuments
        Dim isFlowchartAttached as boolean 
        For Each pD As Humans.ProtocolDocument In attachedDocuments
            If ((FormsManagement.Constants.AttachmentType.Flowchart = pD.Type) and (pD.IsHardCopy or pD.DocumentId >0)) Then
                isFlowchartAttached = True
            End if  
        Next

        if (not isFlowchartAttached) then
            LogMissingItem(-1, -1, "Attachments", string.empty, string.empty, string.empty, "Flowchart must be attached.")
            attachmentsLogItemAdded = true
        end if		

        ' count the number of times they answered the Primary question on the sponorFunding questionnaire.
        Dim primarySponsorCount as integer = 0
        Dim sponsorType as string
        Dim tumorFormExists as Boolean = false
        Dim anesFormExists as Boolean = false
        Dim procFormExists as Boolean = false
        Dim speciesCount as Integer = 0

        intrinsicProtocol.BiologicalAgent = false
        intrinsicProtocol.ToxicChem = false
        intrinsicProtocol.RadioIsotope = false

        For Each questionnaireAnswer As FormsManagement.QuestionnaireAnswer In intrinsicProtocolVersion.QuestionnaireAnswers

            ' Create a validation error if there is a QA with a default name (for multiples) 
            ' --> We do this so that "Move to Rex" doesn't fail when trying to move over blank forms
            ' --> Note that we don't handle Sponsors b/c we only move over the primary sponsor to REX so blank
            ' forms are okay and won't fail the "Move to Rex"
            if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous)
                Dim category as string = "Hazardous Agent Administration and Use"
                Dim description as string = "You have indicated that the study will include a hazardous material.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            else if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Procedures)
                Dim category as string = "Procedures"
                Dim description as string = "You have indicated that the study will include a surgical procedure.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            else if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Tumor)
                Dim category as string = "Tumor Production"
                Dim description as string = "You have indicated that the study will include tumor production.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            else if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Anesthesia)
                Dim category as string = "Anesthesia Regimen"
                Dim description as string = "You have indicated that the study will include an anesthesia regimen.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            else if (questionnaireAnswer.QuestionnaireCategory = FormsManagement.Constants.AnimalsFormCatgory.Anesthesia)
                anesFormExists = true
            else if (questionnaireAnswer.QuestionnaireCategory = FormsManagement.Constants.AnimalsFormCatgory.TumorProduction)
                tumorFormExists = true
            else if (questionnaireAnswer.QuestionnaireCategory = FormsManagement.Constants.AnimalsFormCatgory.Procedures)
                procFormExists = true
            end if

            if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Sponsor Funding" then
                'If the sponsor type is None, then no primary sponsor is required
                Dim sponsorTypes as ArrayList = questionnaireAnswer.GetAnswers("SponsorType")
                if ( sponsorTypes.Count > 0 ) then
                    sponsorType = sponsorTypes(0).Value
                end if

                Dim answers as ArrayList = questionnaireAnswer.GetAnswers("PrimarySponsor")

                if ( answers.Count > 0 ) then
                    Dim primaryAnswer as FormsManagement.Answer = answers(0)
                    if primaryAnswer.Value = "Y" then
                        primarySponsorCount = primarySponsorCount + 1
                    end if
                end if
            end if ' end if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Sponsor Funding" then

            ' check that number of animals are set properly
            if questionnaireAnswer.Name = "Potential Pain and Distress"
                Dim categoryNumber as String = questionnaireAnswer.GetAnswerValue("CatBNum")
                
                if IsNumeric ( categoryNumber ) then
                    speciesCount = FormatNumber(categoryNumber)
                end if

                categoryNumber = questionnaireAnswer.GetAnswerValue("CatCNum")
                if IsNumeric ( categoryNumber ) then
                    speciesCount = speciesCount + FormatNumber(categoryNumber)
                end if

                categoryNumber = questionnaireAnswer.GetAnswerValue("CatDNum")
                if IsNumeric ( categoryNumber ) then
                    speciesCount = speciesCount + FormatNumber(categoryNumber)
                end if

                categoryNumber = questionnaireAnswer.GetAnswerValue("CatENum")
                if IsNumeric ( categoryNumber ) then
                    speciesCount = speciesCount + FormatNumber(categoryNumber)
                end if
            end if
            
            if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Hazardous Agent Administration and Use"
                Dim hazardType as string = questionnaireAnswer.GetAnswerValue("HazardType")
                select case hazardType
                    case "Bio"
                        intrinsicProtocol.BiologicalAgent = true
                    case "Chem"
                        intrinsicProtocol.ToxicChem = true
                    case "Rad"
                        intrinsicProtocol.RadioIsotope = true
                end select
            end if
        next

        if speciesCount <> intrinsicProtocol.NumberOfAnimals then
            Dim category as string = "Potential Pain and Distress"
            Dim description as string = "The sum of the pain category breakdown questions do not equal the total number of animals from the Standard Application."
            Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
            SaveLogItem(logItem)	
        end if
        
        ' If the checkbox on the standard app is checked, but there is no corresponding form, report an error
        Dim stdAnswers as ArrayList = intrinsicProtocolVersion.GetQuestionnaireAnswers(FormsManagement.Constants.AnimalsFormCatgory.InitialStandardApplication)
        if stdAnswers.Count > 0 then
            Dim qa as FormsManagement.QuestionnaireAnswer = stdAnswers(0)

            Dim answers as ArrayList = qa.GetAnswers("NonSx")
            if answers.Count > 0 then
                if answers(0).Value = "Proc" And Not procFormExists then
                    Dim category as string = "Procedures"
                    Dim description as string = "You have indicated that the study will include a surgical procedure.  Please either complete the form or remove it from the study."
                    Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                    SaveLogItem(logItem)	
                end if
            end if
            
            answers = qa.GetAnswers("AnesAgent")
            if answers.Count > 0 then
                if answers(0).Value = "ANES" And Not anesFormExists then
                    Dim category as string = "Anesthesia Regimen"
                    Dim description as string = "You have indicated that the study will include an anesthesia regimen.  Please either complete the form or remove it from the study."
                    Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                    SaveLogItem(logItem)	
                end if
            end if

            answers = qa.GetAnswers("Tumor")
            if answers.Count > 0 then
                if answers(0).Value = "TUMOR" And Not tumorFormExists then
                    Dim category as string = "Tumor Production"
                    Dim description as string = "You have indicated that the study will include tumor production.  Please either complete the form or remove it from the study."
                    Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                    SaveLogItem(logItem)	
                end if
            end if
        end if

        Dim qV as FormsManagement.QuestionnaireVersion

        dim verifiedQuestionnaires as string = "|"
		For Each questionnaireAnswer As FormsManagement.QuestionnaireAnswer In intrinsicProtocolVersion.QuestionnaireAnswers
			qv = questionnaireAnswer.QuestionnaireVersion
			'Check if this type of document was already verified with the attachments
			dim verifyQuestionnaire = "|" + qv.Questionnaire.Name + "|"
			if verifiedQuestionnaires.IndexOf(verifyQuestionnaire) < 0  then
				verifiedQuestionnaires = verifiedQuestionnaires + verifyQuestionnaire
				' Get the documents needed to be attached from the questionnaire version.
				documentsToBeAttached = qV.documents
	            
				'The following for loop checks the availability of the required documents
           		For Each qD As FormsManagement.QuestionDocument In documentsToBeAttached
           			If (qD.Type <> Nothing) Then
               			If (qD.IsRequired) Then
							
       						dim supposedPDCountForQDType as integer = 0
       						dim actualPDCountForQDType as integer = 0

							'Get the type of the question. If the question's type is MultiInput or DropDownMultiSelect, then for each entry, need a enforce a document
							dim isMultiInputOrMultiSelect as boolean = false
							for each item as FormsManagement.QuestionnaireItem in qV.Items
								if (item.Name = qD.ItemName) then
									if (item.Type = FormsManagement.QuestionnaireItem.MultiSelectItemType or item.Type = FormsManagement.QuestionnaireItem.DropDownMultiSelectItemType) then
										isMultiInputOrMultiSelect = true
									end if
									exit for
								end if
							next
					
							'if (questionnaireAnswer.VersionAllowsMultiple) then
								dim similarQAs as ArrayList
								similarQAs = intrinsicProtocolVersion.GetAllQVQAs(questionnaireAnswer.QuestionnaireVersion.Id)
								
								if (not isMultiInputOrMultiSelect) then
									for each qA as FormsManagement.QuestionnaireAnswer in similarQAs
										For each answer as FormsManagement.Answer in qA.GetAnswers(qD.ItemName)
											if (answer.value = qD.ItemValue) then
												
												supposedPDCountForQDType = supposedPDCountForQDType + 1
												exit for
											end if
										Next
									next
								else 
									for each qA as FormsManagement.QuestionnaireAnswer in similarQAs
										supposedPDCountForQDType = supposedPDCountForQDType + questionnaireAnswer.GetAnswers(qD.ItemName).Count
									next
									
								end if
								
								'Get the attached documents from the protocol document.
								For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
									'If the user has opted to send the hard copy of the document,No Log Item should be logged.
									If ((qD.Type = pD.Type) and (pD.IsHardCopy or pD.DocumentId >0)) Then
										actualPDCountForQDType = actualPDCountForQDType + 1
									End if  
								Next 
								
								If supposedPDCountForQDType > actualPDCountForQDType Then
									Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, -1, -1, "Attachments", "Attachments", qD.ItemName, qD.ItemValue, qD.ValidationMessage, false)
									SaveLogItem(logItem)
									attachmentsLogItemAdded = true
								End If
							'end if 'version allows multiple
						End If
					end if
           		Next ' 'end for loop that checks the availability of the required documents
           	End If
		next 'QUESTIONNAIRE ANSWER	

		'verify if all the ProtocolDocument records are either marked as hardcopy or there is an attachment tied to it
		If not attachmentsLogItemAdded then
			For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
				If not (pD.IsHardCopy or pD.DocumentId >0) Then
					LogMissingItem(AttachmentsPageRedirection, AttachmentsPageRedirection, _
							"Attachments", string.empty, string.empty, string.empty, "Attachment missing for " + pD.Name)
				End if  
			Next
		End If

        ' Check that they've answered the Primary Sponsor question only once. 
        if primarySponsorCount <> 1 then
            if primarySponsorCount = 0 and sponsorType <> "None" then
                LogMissingItem(-2, -2, "Sponsor Funding", string.empty, string.empty, string.empty, "The protocol must have a Primary Sponsor. You must indicate this by answering yes to the Primary sponsor question.")			
            else if primarySponsorCount > 1 then
                LogMissingItem(-2, -2, "Sponsor Funding", string.empty, string.empty, string.empty, "You have answered yes to the Primary Sponsor question for more than one sponsor. Only one can be marked as the Primary sponsor.")			
            end if			
        end if

        Dim studyStaffCollection As Humans.StudyStaff = new Humans.StudyStaff(intrinsicCachePolicy)
        studyStaffCollection.Load(intrinsicConnection,intrinsicProtocolProcess.protocolId,intrinsicProtocolProcess.Id)
        Dim studyStaff as ArrayList = studyStaffCollection.GetStudyStaffList()

        ' Check that each staffPerson has a role
        For Each person as Humans.StaffPerson in studyStaff
            if person.Role.trim() = "Principal Investigator" and person.InstitutionalName <> "MGH" then
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
                logItem.QuestionnaireVersionId=0'qV.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.QuestionnaireAnswerId=0'questionnaireAnswer.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.Type ="Staff & Access"
                logItem.Category ="Staff & Access"
                logItem.QuestionName = "PI's organization"
                logItem.Answer =""
                logItem.Description ="The Principal Investigator for a study must belong to MGH." 'qI.ValidationMessage(There exists no validationMessage for this qI,so the Description is hardCoded)
                logItem.Completed =False
                SaveLogItem(logItem)				
            else if person.Role.trim()="" then
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
                logItem.QuestionnaireVersionId=0'qV.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.QuestionnaireAnswerId=0'questionnaireAnswer.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.Type ="Staff & Access"
                logItem.Category ="Staff & Access"
                logItem.QuestionName = "Staff role"
                logItem.Answer =""
                logItem.Description ="Each staff person must be assigned with a role." 'qI.ValidationMessage(There exists no validationMessage for this qI,so the Description is hardCoded)
                logItem.Completed =False
                SaveLogItem(logItem)				
                exit for
            End If				
        Next	

        intrinsicProtocol.Save(intrinsicConnection)
    End Sub

    'Save LogItem
    Sub SaveLogItem(ByVal logItem As Humans.LogItem)
        intrinsicProtocolProcess.SaveLogItem(logItem)
    End Sub

    private function LogMissingItem(byval questionnaireVersionId as integer, byval questionnaireAnswerId as integer, byval logType as string, byval category as string, byval questionName as string, byval answer as string, byval description as string)
        Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
        logItem.QuestionnaireVersionId = questionnaireVersionId
        logItem.QuestionnaireAnswerId = questionnaireAnswerId
        logItem.Type = logType
        logItem.QuestionName = questionName
        logItem.Category = category
        logItem.Answer = answer
        logItem.Description = description
        logItem.Completed =False
        SaveLogItem(logItem)
    end function
					
end module